#coding = utf-8

import torch
import torch.nn as nn


def double_conv(in_channels, out_channels):
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, 3, padding=1),
        #nn.Dropout(0.5),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(inplace=True),
        nn.Conv2d(out_channels, out_channels, 3, padding=1),
        #nn.Dropout(0.5),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(inplace=True)
    )



class UNet(nn.Module):

    def __init__(self, input_channel, n_class):
        super().__init__()

        self.dconv_down1 = double_conv(input_channel, 64)
        self.dconv_down2 = double_conv(64, 128)
        self.dconv_down3 = double_conv(128, 256)
        self.dconv_down4 = double_conv(256, 512)
        self.dconv_down5 = double_conv(512, 1024)



        self.maxpool = nn.MaxPool2d(2)
        #self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
        self.up_sample4 = nn.ConvTranspose2d(1024, 1024, stride=2, kernel_size=2)
        self.up_sample3 = nn.ConvTranspose2d(512, 512, stride=2, kernel_size=2)
        self.up_sample2 = nn.ConvTranspose2d(256, 256, stride=2, kernel_size=2)
        self.up_sample1 = nn.ConvTranspose2d(128, 128, stride=2, kernel_size=2)


        self.dconv_up4 = double_conv(1024 + 512, 512)
        self.dconv_up3 = double_conv(256 + 512, 256)
        self.dconv_up2 = double_conv(128 + 256, 128)
        self.dconv_up1 = double_conv(128 + 64, 64)

        self.conv_last = nn.Conv2d(64, n_class, 1)

    def forward(self, x):
        conv1 = self.dconv_down1(x)
        x = self.maxpool(conv1)


        conv2 = self.dconv_down2(x)
        x = self.maxpool(conv2)


        conv3 = self.dconv_down3(x)
        x = self.maxpool(conv3)


        conv4 = self.dconv_down4(x)
        x = self.maxpool(conv4)


        x = self.dconv_down5(x)

        x = self.up_sample4(x)
        x = torch.cat([x, conv4], dim=1)
        x = self.dconv_up4(x)

        x = self.up_sample3(x)
        x = torch.cat([x, conv3], dim=1)
        x = self.dconv_up3(x)

        x = self.up_sample2(x)
        x = torch.cat([x, conv2], dim=1)
        x = self.dconv_up2(x)

        x = self.up_sample1(x)
        x = torch.cat([x, conv1], dim=1)
        x = self.dconv_up1(x)


        out = self.conv_last(x)

        return out

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
                m.weight.data.normal_(0, 0.05)
                if m.bias is not None:
                    m.bias.data.fill_(0.1)
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.weight.data.normal_(0, 0.01)
                m.bias.data.zero_()
